var express = require('express');
var router = express.Router();
// 导入jwt
const jwt = require('jsonwebtoken')
const {secret}=require('../../config/config')

//导入 用户的模型
const UserModel = require('../../models/UserModel');
const md5 = require('md5');
//注册
router.get('/reg', (req, res) => {
    //响应 HTML 内容，auth/reg表示views/auth/reg.ejs
    res.render('auth/reg');
});
//登录操作
router.post('/login', (req, res) => {
    //获取用户名和密码
    let { username, password } = req.body;
    //查询数据库
    UserModel.findOne({ username: username, password: md5(password) }, (err, data) => {
        //判断
        if (err) {
            res.json({
                code: '2001',
                msg: '数据库读取时报',
                data: err
            })
            return
        }
        //判断 data
        if (!data) {
            res.json({
                code: '2002',
                msg: '用户或者密码错误',
                data: null
            })
            return
        }
        //写入session
        const username = data.username;
        const _id = data._id;
        const token = jwt.sign({ username: username, _id: _id }, secret, {
            expiresIn: 60 * 60 * 60 * 24, //单位是秒
        })
        //登录成功响应
        res.json({
            code: '0000',
            msg: '登录成功',
            data: token
        })
    })

});

//退出登录
router.post('/logout', (req, res) => {
    //销毁 session
    req.session.destroy(() => {
        res.render('success', { msg: '退出成功', url: '/login' });
    })
});

module.exports = router;
